import { getCartInfo } from "../../../../api/api"
import React, { useState, useContext, useEffect, useRef } from "react";
import Link from "next/link";
import CartContext from "../../../../helpers/cart";
import { Container, Row, Col, Media, Input, Modal, ModalHeader, ModalBody, Form, Label, Button, List, Tooltip } from "reactstrap";
import { CurrencyContext } from "../../../../helpers/Currency/CurrencyContext";
import cart from "../../../../public/assets/images/icon-empty-cart.png";
// import { getCartInfo } from "../.."
import { fileServerUrl } from "../../../../config/index.json";
import { getTwoDecimal } from "../../../../tools/tools";
import { changeProductCount, removeCartProduct } from "../../../../api/api";
import { debounce } from "lodash";
import { toast } from "react-toastify";
import { useRouter } from 'next/router';
import { unkownImage } from '../../../../public/assets/images/unkownImage/default768A864.jpg'

const AdminProductBinListPage = () => {
  const context = useContext(CartContext);
  const cartItems = context.state;
  const maxImgSize = 1024 * 1024 * 5;
  const curContext = useContext(CurrencyContext);
  const symbol = curContext.state.symbol;
  // const total = context.cartTotal;
  // const removeFromCart = context.removeFromCart;
  const [quantity, setQty] = useState(1);
  const [quantityError, setQuantityError] = useState(false);
  const updateQty = context.updateQty;

  const [cartList, setCartList] = useState([]);
  const [total, setTotal] = useState(0);
  const [qtyList, setQtyList] = useState([]);
  const [lineTotal, setLineTotal] = useState(0);
  const [isOpen, setIsOpen] = useState(false);
  const [imgList, setImgList] = useState([]);
  const [imgBase64List, setImgBase64List] = useState([]);

  const debounceRef = useRef(null);
  const router = useRouter();

  useEffect(() => {
    var userInfo = localStorage.getItem("XYCLogin");
    if (userInfo) {
      if (JSON.parse(userInfo).user_guid) {
        getCartInfo({ userGuid: JSON.parse(userInfo).user_guid }).then(res => {
          setCartList(res.data);
          let to = Number(0);
          var qtys = [];
          res.data.map(item => {
            to += parseFloat(item.price * item.quantity);
            qtys.push({
              "product_id": item.product_id,
              "quantity": item.quantity,
              "product_stock": item.product_stock,
              "price": item.price
            })
          })
          setTotal(getTwoDecimal(`${to}`));
          setQtyList(qtys);
        });
      }
    }
  }, [window.onload])

  useEffect(() => {

    var product = localStorage.getItem("XYCLogin")
    if (!product) {
      toast.error("Please Login To Shopping!");
      router.push("/");
    }

    debounceRef.current = debounce((item, quantity) => {
      changeProductCount({
        product_id: item.product_id,
        quantity: quantity
      })
    }, 1000);

    return () => {
      if (debounceRef.current) {
        debounceRef.current.cancel();
      }
    };
  }, [])

  const handleQtyUpdate = (item, quantity) => {
    if (quantity > 0 && quantity) {
      debounceRef.current(item, quantity);
      var newQtys = [];
      qtyList.map(q => {
        if (q.product_id != item.product_id)
          newQtys.push(q);
      });
      newQtys.push({
        "product_id": item.product_id,
        "quantity": quantity,
        "product_stock": item.product_stock,
        "price": item.price
      });
      setQtyList(newQtys);

      var newTotal = 0;
      newQtys.map(nq => {
        newTotal += parseFloat(getTwoDecimal(`${parseFloat(nq.price) * parseFloat(nq.quantity)}`))
      })
      setTotal(getTwoDecimal(`${newTotal}`))
    }
  };

  const removeProduct = (item) => {
    setCartList(v => v.filter(p => p.product_id != item.product_id));
    removeCartProduct({ "product_id": item.product_id });
    toast.success("Product remove succeed!");
    var newTotal = 0;
    qtyList.map(nq => {
      if (nq.product_id != item.product_id) {
        newTotal += parseFloat(getTwoDecimal(`${parseFloat(nq.price) * parseFloat(nq.quantity)}`))
      }
    })
    setQtyList(v => v.filter(p => p.product_id != item.product_id));
    console.log(newTotal)
    setTotal(getTwoDecimal(`${newTotal}`))
  }

  const handleFileChange = (event) => {
    // event.target.files 是一个 FileList 对象，它包含了用户选择的文件
    if (event.target.value != "" && imgList.length < 3) {
      var file = event.target.files[0];
      if (isImageFile(event.target.value)) {
        if (file.size < maxImgSize) {
          var reader = new FileReader();
          reader.readAsDataURL(file);
          reader.onload = () => {
            var base64 = reader.result.replace(/^data:image\/\w+;base64,/, '');
            if (base64 != undefined) {
              if (base64.length > 0) {
                setImgBase64List(imgs => [...imgs, base64])
              }
            }
          };
          setImgList(imgs => [...imgs, event.target.value])
        }
        else {
          toast.error("Image Can Not Larger Then 5 MB!")
        }
      };
    }
  };

  const isImageFile = (filename) => {
    const extensions = ['.jpg', '.jpeg', '.png'];
    return extensions.some(extension => filename.toLowerCase().endsWith(extension));
  }

  const handleUploadBtnOnclick = () => {
    document.getElementById("uploadRealBtn").click();
  }

  const handleDeleteImageItem = (id) => {
    setImgList(imgs => {
      return imgs.filter((v, index) => index != id);
    });
    setImgBase64List(imgs => {
      return imgs.filter((v, index) => index != id);
    });
  }

  return (
    <div>
      <Modal isOpen={isOpen} centered size="lg">
        <ModalHeader >Add Product
        </ModalHeader>
        <ModalBody>
          <div className="admin-user-form">
            <Row>
              <Col sm="12">
                <Form className="theme-form">
                  <Row>
                    <Col sm="12">
                      <List type="unstyled">
                        {
                          imgList.length > 0 ? <><h4>Product List:</h4> {imgList.map((item, id) => {
                            return <div key={id}><Button size="sm" style={{ marginRight: 20 }} onClick={() => handleDeleteImageItem(id)}>Delete</Button><li key={id}>{item}</li></div>
                          })}</> :
                            <li key={"empty"}>Please Upload 768x864 Images For Products, it will be limited below 5mb.</li>
                        }
                      </List>
                    </Col>
                  </Row>
                  <Row className="admin-product-list-upload-img-btn">
                    <Col sm="4">
                      <input type="file" id="uploadRealBtn" name="uploadRealBtn" accept="image/jpeg, image/png" style={{ display: 'none' }} onChange={handleFileChange} />
                      <Button color="primary" onClick={handleUploadBtnOnclick} disabled={imgList.length >= 3}>Upload</Button>
                    </Col>
                  </Row>

                  <Row>
                    <Col md="3">
                      <Label for="lName">Product Id</Label>
                      <Input type="text" className="form-control" id="lname" name="lname" placeholder="Email Adress" disabled value="12345678@gmail.com" />
                    </Col>
                    <Col md="3">
                      <Label for="lName">Product Name</Label>
                      <Input type="text" className="form-control" id="lname" name="lname" placeholder="Email Adress" defaultValue="12345678@gmail.com" />
                    </Col>
                    <Col md="3">
                      <Label for="fname">Product Price</Label>
                      <Input type="text" className="form-control" id="fname" name="fname" placeholder="First Name"
                        defaultValue={"Test First Name"} />
                    </Col>
                    <Col md="3">
                      <Label for="fname">Product Quantity</Label>
                      <Input type="text" className="form-control" id="fname" name="fname" placeholder="Last Name"
                        defaultValue={"Test Last Name"} />
                    </Col>
                  </Row>
                  <Row>
                    <Col md="4">
                      <Label for="fname">Year</Label>
                      <Input type="text" className="form-control" id="ugroup" name="ugroup" placeholder="First Name" />
                    </Col>
                    <Col md="4">
                      <Label for="fname">Brand</Label>
                      <Input type="text" className="form-control" id="password" name="password" placeholder="change password" />
                    </Col>
                    <Col md="4">
                      <Label for="fname">Model</Label>
                      <Input type="text" className="form-control" id="ugroup" name="ugroup" placeholder="First Name" />
                    </Col>
                  </Row>
                  <Row>
                    <Col md="4">
                      <Label for="fname">Engine</Label>
                      <Input type="text" className="form-control" id="ugroup" name="ugroup" placeholder="First Name" />
                    </Col>
                    <Col md="4">
                      <Label for="fname">Fuel Type</Label>
                      <Input type="text" className="form-control" id="password" name="password" placeholder="change password" />
                    </Col>
                    <Col md="4">
                      <Label for="fname">Update Date</Label>
                      <Input type="text" className="form-control" id="ugroup" name="ugroup" placeholder="First Name" disabled value={"2024-07-12"} />
                    </Col>
                  </Row>
                  <Row>
                    <Col md="12">
                      <Label for="deliverAddress">Product Detail</Label>
                      <Input type="text" className="form-control" id="productDetail" name="productDetail" placeholder="Product Detail, Max length: 100 digits." maxLength={100}
                        required="" />
                    </Col>
                    <Col md="12">
                      <Label for="zipCode">Product Description</Label>
                      <Input type="textarea" style={{ height: 100 }} className="form-control" id="productDescription" name="productDescription" placeholder="Product Description, Max length: 400 digits." maxLength={400}
                        required="" />
                    </Col>
                  </Row>
                  <div className="admin-user-form-btn-list">
                    <Row>
                      <Col md="6">
                      </Col>
                      <Col md="3">
                        <a href={null} style={{ width: 170, height: 40, fontSize: 12, lineHeight: 1 }} className="btn btn-solid" >Save</a>
                      </Col>
                      <Col md="3">
                        <a href={null} onClick={() => { setIsOpen(false) }} style={{ width: 170, height: 40, fontSize: 12, lineHeight: 1 }} className="btn btn-solid" >Cancel</a>
                      </Col>
                    </Row>
                  </div>
                </Form>
              </Col>
            </Row>
          </div>
        </ModalBody>
      </Modal>
      <div>
        <Row className="admin-user-btn-list">
          <Col md="3"><Input type="text" className="form-control" id="lname" name="lname" placeholder="Please enter product name, Year, Brand..." /></Col>
          <Col md="1"><a href={null} style={{ width: 120, height: 40, fontSize: 12, lineHeight: 1 }} className="btn btn-solid" >Search</a></Col>
          <Col md="1"><a href={null} style={{ width: 130, height: 40, fontSize: 12, lineHeight: 1 }} className="btn btn-solid" >Add User</a></Col>
        </Row>
      </div>
      {cartList && cartList.length > 0 ? (
        <section className="cart-section section-b-space">
          <Container>
            <Row>
              <Col sm="12">
                <table className="table cart-table table-responsive-xs">
                  <thead>
                    <tr className="table-head">
                      {/* <th scope="col">image</th> */}
                      <th scope="col">product id</th>
                      <th scope="col">product name</th>
                      <th scope="col">product price</th>
                      <th scope="col">product quantity</th>
                      <th scope="col">action</th>
                    </tr>
                  </thead>
                  {cartList.map((item, index) => {
                    return (
                      <tbody key={index}>
                        <tr>
                          <td>
                            <Link href={`/product-details/` + item.product_id}>
                              <a>{item.product_name}</a>
                            </Link>
                          </td>
                          <td>
                            <h2>
                              {item.price}
                            </h2>
                          </td>
                          <td>
                            <h2>
                              {item.price}
                            </h2>
                          </td>

                          <td>
                            {item.quantity}
                          </td>
                          <td>
                            <Button className="admin-product-acion" onClick={() => { setIsOpen(true) }}>Edit</Button>
                            <Button className="admin-product-acion">Delete</Button>
                          </td>
                        </tr>
                      </tbody>
                    );
                  })}
                </table>
              </Col>
            </Row>
          </Container>
        </section>
      ) : (
        <section className="cart-section section-b-space">
          <Container>
            <Row>
              <Col sm="12">
                <div>
                  <div className="col-sm-12 empty-cart-cls text-center">
                    <Media
                      src={cart}
                      className="img-fluid mb-4 mx-auto"
                      alt=""
                    />
                    <h3>
                      <strong>Product is Empty</strong>
                    </h3>
                    <h4>Add More Product.</h4>
                  </div>
                </div>
              </Col>
            </Row>
          </Container>
        </section>
      )}
      <div className="admin-page-select-btn">
        <Button className="page-select-btn1" onClick="">Last Page</Button><span className="page-select-label">{"1"} IN {"5"}</span><Button className="page-select-btn2" onClick="">Next Page</Button>
      </div>
    </div>
  );
};

export default AdminProductBinListPage;
